package fr.utbm.tx52.stamp.ui.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import fr.utbm.tx52.stamp.R;
import fr.utbm.tx52.stamp.adapter.ContactsAdapter;
import fr.utbm.tx52.stamp.logic.Contact;
import fr.utbm.tx52.stamp.logic.DataManager;
import java.util.*;

/**
 * Fragment used for the left tab in medium mode and not used in low mode
 * Display the list of contact
 *
 * @author GREA Antoine
 * @author TISSERAND Geoffrey
 */
public class AddressBook extends ListFragment
{

	public static void addContactInWaitingList(String string)
	{
		waitingList.add(string);
	}

	private void parseWaitingList()
	{

		for (String number : waitingList)
		{

			final Contact contact = Contact.getContactsByPhone(getActivity(), number);

			Log.d(getClass().getName(), contact.getName());

			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setMessage(getString(R.string.add_contact_permision, (contact != null ? contact.getName() : ""))).setCancelable(false).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener()
			{

				public void onClick(DialogInterface dialog, int id)
				{
					DataManager.addAssociatedContacts(getActivity(), contact);
					drawContactsList();
				}
			}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener()
			{

				public void onClick(DialogInterface dialog, int id)
				{
					dialog.cancel();
				}
			});
			builder.create().show();
		}

		waitingList.clear();
	}
	private static List<String> waitingList = new ArrayList<String>(); // phoneNumbers
	int mCurCheckPosition = 0;
	private static Map<Activity, AddressBook> instances = new HashMap<Activity, AddressBook>();

	public static AddressBook get(Activity activity)
	{
		return instances.get(activity);
	}
	private ContactsAdapter adapter;
	private List<Contact> contacts;
	private boolean selectMode = false;

	public ContactsAdapter getAdapter()
	{
		return adapter;
	}

	public AddressBook()
	{
	}

	public AddressBook(boolean selectMode)
	{
		this.selectMode = selectMode;
	}

	@Override
	public void onActivityCreated(Bundle savedState)
	{
		super.onActivityCreated(savedState);
		instances.put(getActivity(), this);
		adapter = new ContactsAdapter(getActivity(), getAssociatedContactList(getActivity()), selectMode ? ContactsAdapter.Listener.SELECT : ContactsAdapter.Listener.REMOVE);
		setListAdapter(adapter);
		if (savedState != null)
		{
			// Restore last state for checked position.
			mCurCheckPosition = savedState.getInt("curChoice", 0);
		}
		if (selectMode)
		{
			getListView().setItemsCanFocus(false);
			getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
		}
	}

	/**
	 * Obtient la liste des contacts associ�s
	 *
	 * @param a L'activit� qui demande la liste
	 *
	 * @return La liste des contacts associ�s � l'application
	 */
	public static List<Contact> getAssociatedContactList(Activity activity)
	{
		List<Contact> l = new ArrayList<Contact>();

		Map<Integer, String> associatedContacts = DataManager.loadAssociatedContacts(activity.getApplicationContext());
		Set<Integer> contactsIds = associatedContacts.keySet();

		for (Integer id : contactsIds)
		{

			Uri dataUri = ContactsContract.Data.CONTENT_URI;

			String[] projection = new String[]
			{
				ContactsContract.Contacts.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID
			};

			Cursor c = activity.getContentResolver().query(
				dataUri,
				projection,
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id.toString(),
				null, null);

			if (c.moveToFirst())
			{

				String name = c.getString(0);

				Bitmap photo = Contact.loadContactPhoto(activity.getApplicationContext(), Long.decode(id.toString()));

				Contact co = new Contact(
					name,
					photo,
					id.toString(),
					associatedContacts.get(id));

				l.add(co);
			}
		}

		Collections.sort(l);

		return l;
	}

	/**
	 * Affiche la liste des contacts dans le tableau
	 */
	public void drawContactsList()
	{
		contacts = getAssociatedContactList(getActivity());
		setListAdapter(new ContactsAdapter(getActivity(), contacts, ContactsAdapter.Listener.REMOVE));
		// TODO Toast if empty
	}

	@Override
	public void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);
		outState.putInt("curChoice", mCurCheckPosition);
	}

	@Override
	public void onListItemClick(ListView l, View v, int pos, long id)
	{
	}
}
